from datetime import datetime
import os
import string
import sys
import json
from data_reader.DataReader import DataReader
from liblas import header, file
import liblas

class Las:

    def load_data(self, data_dir:string, reader_name:string):
        loadermodule = "data_reader." + reader_name
        exec('from ' + loadermodule + ' import ' + reader_name)
        reader_class = getattr(sys.modules[loadermodule], reader_name)
        reader = reader_class(data_dir)

        # 1. Create a new header
        h = header.Header()
        h.data_format_id = 1
        h.minor_version = 1

        sweep_index = 0
        while reader.has_more_sweep():
            sweep_index += 1
            f = file.File(str(sweep_index) + '.las', mode="w", header=h)
            x_arr, y_arr, z_arr = reader.read_sweep()
            tmsp = reader.read_timestamp()
            for i in range(len(x_arr)):
                pt = liblas.point.Point()
                pt.x = x_arr[i]
                pt.y = y_arr[i]
                pt.z = z_arr[i]
                pt.time = datetime.fromtimestamp(tmsp)
                f.write(pt)
        
        f.close()

if __name__ == '__main__':
    with open(os.getcwd() + '/config.json', 'r') as f:
        config = json.load(f)

    data_base_path = config["data_base_path"]
    test_case = config["test_case"]
    for test_case in config["test_case"]:
        test_case = config["collect_dataset"][test_case]
        Las().load_data(test_case)
